const {server,token} = require('../config');
const os=require('os');
const pool = require('./mysql');
const jwt=require('jsonwebtoken');
// const express=require('express');

/* class Router{
    route=express.Router();
    getRoute(){
        return this.route;
    }
    post(api,callback){
        this.route.post(api,(req,res)=>{
            callback(req,res);
        })
    }
    get(api,callback){
        this.route.get(api,(req,res)=>{
            callback(req,res)
        })
    }
} */
const fun={
    //初始化的一个router类
    /* getRouter(){
        return new Router();
    }, */
    //加密token
    getToken(data){
        return 'Bearer ' + jwt.sign(data, token.secretKey, { expiresIn: token.time })
    },
    //执行sql语句
    perfromSql(sql,...parm) {
        return new Promise((resolve, reject) => {
            pool.getConnection((err, conn) => {
                if (err) {
                    reject(err);
                    return;
                }
                conn.query(sql,parm,(queryErr,result)=>{
                    conn.release();
                    if(queryErr){
                        reject(queryErr);
                        return;
                    }
                    resolve(result);
                })
            })
        })
    },
    //发送成功的返回
    send(res, ...arr) {
        let data;
        let message = '成功';
        arr.forEach(item => {
            if (typeof (item) == 'string') {
                message = item;
            } else {
                data = item;
            }
        })
        res.send({
            code: 0,
            message: message,
            data: data
        })
    },
    //发送失败的返回
    sendErr(res, ...arr) {
        let errCode = server.errCode;
        let data = {};
        let message = '';
        arr.forEach(item => {
            switch (typeof (item)) {
                case 'number':
                    errCode = item;
                    break;
                case 'string':
                    message = item;
                    break;
                case 'object':
                    data = item;
                    break;
                default:
                    throw new Error('sendErr:参数错误').catch(err => {
                        console.error("sendErr:参数错误", err.message);
                    })
            }
        })
        res.status(errCode).send({
            code: 1,
            data: data,
            message: message
        })
    },
    //拿到服务器内网ip
    getIp() {
        var interfaces = os.networkInterfaces();
        for (var devName in interfaces) {
            var iface = interfaces[devName];
            for (var i = 0; i < iface.length; i++) {
                var alias = iface[i];
                if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                    return alias.address;
                }
            }
        }
        return ''
    }
}

module.exports = {...fun}